package example.zxing;

import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.ResultPoint;
import com.google.zxing.client.android.BeepManager;
import com.journeyapps.barcodescanner.BarcodeCallback;
import com.journeyapps.barcodescanner.BarcodeResult;
import com.journeyapps.barcodescanner.DecoratedBarcodeView;
import com.journeyapps.barcodescanner.DefaultDecoderFactory;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import example.zxing.templist.LogUtils;
import example.zxing.templist.ScanBean;
import example.zxing.templist.ScanResultAdapter;

/**
 * This sample performs continuous scanning, displaying the barcode and source image whenever
 * a barcode is scanned.
 */
public class ContinuousCaptureActivity extends Activity {
    private static final String TAG = ContinuousCaptureActivity.class.getSimpleName();
    private DecoratedBarcodeView barcodeView;
    private BeepManager beepManager;
    private String lastText;

    private TextView mTvResultList;
    private int totleCount;
    private long firstTime = 0;

    private SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HH:mm:ss");

    private RecyclerView mRecycleView;
    private ScanResultAdapter recycleAdapter;
    private List<ScanBean> mList;
    private List<ScanBean> tempList;

    private BarcodeCallback callback = new BarcodeCallback() {
        @Override
        public void barcodeResult(BarcodeResult result) {
            long divInt = System.currentTimeMillis() - firstTime;
            Log.i(TAG, "divide->" + divInt + " | timeStamp:" + result.getTimestamp());

            if (divInt < 1600) {
                return;
            }
            firstTime = System.currentTimeMillis();

//            if (result.getText() == null || result.getText().equals(lastText)) {
//                return; // Prevent duplicate scans
//            }

            lastText = result.getText();

            Log.e("scan_result", "result.getText():" + result.getText());

            beepManager.setBeepEnabled(true);
            beepManager.setVibrateEnabled(true);
            beepManager.playBeepSoundAndVibrate();

            LogUtils.appendPieceOfLog(df.format(result.getTimestamp()) + "\t | \t" + result.getText());

            // verison:1
//            totleCount++;
//            if (totleCount <= 5) {
//                mTvResultList.setText(result.getText() + "\n" + mTvResultList.getText().toString().trim());
//            } else {
//                totleCount = 1;
//                String rawStr = mTvResultList.getText().toString().trim();
//                Layout tvResultLayout = mTvResultList.getLayout();
//                int fourLineEnd = tvResultLayout.getLineEnd(3);
//                String oldStr = rawStr.substring(0, fourLineEnd); //指定行的内容
//                mTvResultList.setText(result.getText() + "\n" + oldStr);
//            }

            // verison:2
            addOneNewItem(result);
            mList.clear();
            mList.addAll(tempList);
            Collections.reverse(mList);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    recycleAdapter.notifyDataSetChanged();
                }
            });
        }

        @Override
        public void possibleResultPoints(List<ResultPoint> resultPoints) {
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.activity_continuous_scan);

        barcodeView = (DecoratedBarcodeView) findViewById(R.id.barcode_scanner);
        Collection<BarcodeFormat> formats = Arrays.asList(BarcodeFormat.QR_CODE, BarcodeFormat.CODE_39);
        barcodeView.getBarcodeView().setDecoderFactory(new DefaultDecoderFactory(formats));
        barcodeView.decodeContinuous(callback);

        beepManager = new BeepManager(this);

        initList();
    }

    private void initList() {
        mTvResultList = (TextView) findViewById(R.id.tv_scan_result);
        firstTime = System.currentTimeMillis();
        barcodeView.setStatusText("默认: 1.5秒扫描一次");

        mRecycleView = (RecyclerView) findViewById(R.id.recycle_list_select_room);
        mRecycleView.setLayoutManager(new LinearLayoutManager(this));
        mRecycleView.setHasFixedSize(true);
        mList = new ArrayList<>();
        tempList = new ArrayList<>();
        recycleAdapter = new ScanResultAdapter(this, mList);
        mRecycleView.setAdapter(recycleAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        barcodeView.resume();

        if (ContextCompat.checkSelfPermission(ContinuousCaptureActivity.this,
                android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(ContinuousCaptureActivity.this,
                    new String[]{android.Manifest.permission.CAMERA}, 0x02);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        barcodeView.pause();
    }

    public void pause(View view) {
        barcodeView.pause();
    }

    public void resume(View view) {
        barcodeView.resume();
    }

    public void triggerScan(View view) {
        barcodeView.decodeSingle(callback);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return barcodeView.onKeyDown(keyCode, event) || super.onKeyDown(keyCode, event);
    }

    private void addOneNewItem(BarcodeResult re) {
        if (tempList.size() >= 5) {
            tempList.remove(0);
        }
        tempList.add(new ScanBean(re.getText(), re.getTimestamp()));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        LogUtils.CloseCurrentLogFile();
        Log.e(TAG, "## onDestroy");
    }
}
